package web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.IArtist;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import dao.IArtistDAO;

/**
 * @spring.bean name="artistListController"
 * @spring.property name="artistService" ref="ARTIST_SERVICE"
 * @author ipeel
 *
 */
public class ArtistListController implements Controller {

    /** Logger for this class and subclasses */
    protected final Log logger = LogFactory.getLog(getClass());
    private IArtistDAO artistService;
    
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	String view = null;
    	List<IArtist> artistList = null;
    	
    	String letter = request.getParameter("letter");
    	String artistId = request.getParameter("artistId");
    	String name = request.getParameter("name");

    	if(letter != null) {
    		if("All".equals(letter)) {
    			artistList = artistService.getArtists();
    		} else {
    			artistList = artistService.getArtistsByLetter(letter);
    		}
    		
    		view = IConstants.Views.ARTIST_LIST;
    	}
    	
    	if(artistId != null) {
    		IArtist artist = artistService.getArtistbyId(new Integer(artistId));
    		artistList = new ArrayList<IArtist>();
    		artistList.add(artist);
    		view = IConstants.Views.ARTIST_LIST;
    	}
    	
    	if(name != null) {
    		artistList = artistService.getArtistsByName("%"+name+"%");
    		view = IConstants.Views.ARTIST_SEARCH_RESULTS;
    	}
    	
    	Map<String, Object> beans = new HashMap<String, Object>();    	
    	beans.put("artistList", artistList);
	    
        return new ModelAndView(view, beans);
    }

	/**
	 * @return Returns the artistService.
	 */
	public IArtistDAO getArtistService() {
		return artistService;
	}

	/**
	 * @param artistService The artistService to set.
	 */
	public void setArtistService(IArtistDAO artistService) {
		this.artistService = artistService;
	}
}